package com.htd.base.common.config.interceptor;


import com.htd.base.common.config.LsCoreProperties;
import com.htd.base.common.config.local.TranslateThreadLocal;
import com.htd.base.common.constant.BaseConstant;
import com.htd.base.modules.translate.enumeration.LangCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * 多语言拦截器
 *
 * @author Mark sunlightcs@gmail.com
 */
@Slf4j
@Component
public class LsCoreHttpInterceptor implements HandlerInterceptor {

    @Autowired
    private LsCoreProperties lsCoreProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        // 开启多语言功能
        if (lsCoreProperties.getBase().language().getOpen()){
            log.debug("[Trans. plugin] 多語言資料庫功能開啟");
            // 截获请求头中的多语系设定
            String langCode = request.getHeader(BaseConstant.HEADER_LANG_CODE);
            // 请求头未设定语种，或语种代码无效，则使用默认语种
            if (StringUtils.isBlank(langCode) || !LangCodeEnum.contains(langCode)) {
                langCode = lsCoreProperties.getBase().language().default_locale();
                log.debug("[Trans. plugin] 使用默認語種:{}", langCode);
            } else {
                // 兼容舊版本語種代碼
                langCode = LangCodeEnum.convertLangCode(langCode);
            }
            map.put(BaseConstant.ThreadLocal.TRAN_SWITCH, BaseConstant.ThreadLocal.TRAN_SWITCH_OPEN);
            map.put(BaseConstant.ThreadLocal.TRAN_LANG_CODE, langCode);
            TranslateThreadLocal.set(map);
        } else {
            log.debug("[Trans. plugin] 多語言資料庫功能未開啟");
            map.put(BaseConstant.ThreadLocal.TRAN_SWITCH, BaseConstant.ThreadLocal.TRAN_SWITCH_CLOSE);
            TranslateThreadLocal.set(map);
        }
        return true;
    }
    /**
     * 请求处理后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完后，需要清空 MyThreadLocal 集合数据
        // 避免 OOM
        TranslateThreadLocal.remove();
        log.debug("[Trans. plugin] MyThreadLocal.remove()");
    }
}
